package com.office.web.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import com.office.common.annotation.Log;
import com.office.common.core.controller.BaseController;
import com.office.common.core.domain.PageQuery;
import com.office.common.core.domain.R;
import com.office.common.core.page.TableDataInfo;
import com.office.common.core.validate.QueryGroup;
import com.office.common.enums.BusinessType;
import com.office.system.domain.bo.SysOssBo;
import com.office.system.domain.vo.SysOssVo;
import com.office.system.service.IDataCleaningService;
import com.office.system.service.ISysOssService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;

/**
 * 文件上传 控制层
 *
 * @author 数字牧马人
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/oss")
@Tag(name = "大文件上传")
public class SysOssController extends BaseController {

    private final ISysOssService iSysOssService;
    private final IDataCleaningService dataCleaningService;

    /**
     * 查询OSS对象存储列表
     */
    @SaCheckPermission("system:oss:list")
    @GetMapping("/list")
    public TableDataInfo<SysOssVo> list(@Validated(QueryGroup.class) SysOssBo bo, PageQuery pageQuery) {
        return iSysOssService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询OSS对象基于id串
     *
     * @param ossIds OSS对象ID串
     */
    @SaCheckPermission("system:oss:list")
    @GetMapping("/listByIds/{ossIds}")
    public R<List<SysOssVo>> listByIds(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ossIds) {
        List<SysOssVo> list = iSysOssService.listByIds(Arrays.asList(ossIds));
        return R.ok(list);
    }

    /**
     * 上传OSS对象存储
     *
     * @param file 文件
     */
    @SaCheckPermission("system:oss:upload")
    @Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, Object>> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }

        // 检查文件大小
        long maxSize = 200 * 1024 * 1024; // 200MB
        if (file.getSize() > maxSize) {
            return R.fail("文件大小不能超过200MB");
        }

        try {
            // 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();

            // 进行数据清洗
            Map<String, Object> cleaningResult = dataCleaningService.cleanData(file);

            // 如果清洗结果有错误，直接返回错误信息
            if ("error".equals(cleaningResult.get("status"))) {
                return R.fail((String) cleaningResult.get("message"));
            }

            // 获取清洗后的数据
            List<String> cleanedData = (List<String>) cleaningResult.get("cleanedData");
            if (cleanedData != null && !cleanedData.isEmpty()) {
                // 如果是PDF、Word、Excel文件，使用清洗后的Base64数据上传
                if ("pdf".equals(fileExtension) || "xlsx".equals(fileExtension) || "xls".equals(fileExtension) ||
                    "docx".equals(fileExtension) || "doc".equals(fileExtension)) {
                    byte[] fileBytes = Base64.getDecoder().decode(cleanedData.get(0));
                    MultipartFile cleanedFile = new MultipartFile() {
                        @Override
                        public String getName() { return "file"; }
                        @Override
                        public String getOriginalFilename() { return originalFilename; }
                        @Override
                        public String getContentType() { return file.getContentType(); }
                        @Override
                        public boolean isEmpty() { return fileBytes.length == 0; }
                        @Override
                        public long getSize() { return fileBytes.length; }
                        @Override
                        public byte[] getBytes() { return fileBytes; }
                        @Override
                        public java.io.InputStream getInputStream() { return new ByteArrayInputStream(fileBytes); }
                        @Override
                        public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
                            java.nio.file.Files.write(dest.toPath(), fileBytes);
                        }
                    };
                    SysOssVo oss = iSysOssService.upload(cleanedFile);
                    Map<String, Object> result = new HashMap<>();
                    result.put("url", oss.getUrl());
                    result.put("fileName", oss.getOriginalName());
                    result.put("ossId", oss.getOssId().toString());
                    result.put("cleaningResult", cleaningResult);
                    return R.ok(result);
                }
            }

            // 对于其他类型的文件，使用原始的处理逻辑
            byte[] cleanedBytes = (byte[]) cleaningResult.get("cleanedBytes");
            if (cleanedBytes != null) {
                String contentType = file.getContentType();

                // 创建新的MultipartFile
                MultipartFile cleanedFile = new MultipartFile() {
                    @Override
                    public String getName() {
                        return "file";
                    }

                    @Override
                    public String getOriginalFilename() {
                        return originalFilename;
                    }

                    @Override
                    public String getContentType() {
                        return contentType;
                    }

                    @Override
                    public boolean isEmpty() {
                        return cleanedBytes.length == 0;
                    }

                    @Override
                    public long getSize() {
                        return cleanedBytes.length;
                    }

                    @Override
                    public byte[] getBytes() throws IOException {
                        return cleanedBytes;
                    }

                    @Override
                    public java.io.InputStream getInputStream() throws IOException {
                        return new ByteArrayInputStream(cleanedBytes);
                    }

                    @Override
                    public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
                        java.nio.file.Files.write(dest.toPath(), cleanedBytes);
                    }
                };

                // 上传清洗后的文件
                SysOssVo oss = iSysOssService.upload(cleanedFile);
                Map<String, Object> result = new HashMap<>();
                result.put("url", oss.getUrl());
                result.put("fileName", oss.getOriginalName());
                result.put("ossId", oss.getOssId().toString());
                result.put("cleaningResult", cleaningResult);

                return R.ok(result);
            }

            // 如果没有清洗后的数据，使用原始文件上传
            SysOssVo oss = iSysOssService.upload(file);
            Map<String, Object> result = new HashMap<>();
            result.put("url", oss.getUrl());
            result.put("fileName", oss.getOriginalName());
            result.put("ossId", oss.getOssId().toString());
            result.put("cleaningResult", cleaningResult);

            return R.ok(result);
        } catch (IOException e) {
            // 如果是数据清洗的错误，直接返回错误信息
            if (e.getMessage().contains("数据文件中的错误数量过多")) {
                return R.fail(e.getMessage());
            }
            return R.fail("文件处理失败：" + e.getMessage());
        }
    }

    /**
     * 下载OSS对象
     *
     * @param ossId OSS对象ID
     */
    @SaCheckPermission("system:oss:download")
    @GetMapping("/download/{ossId}")
    public void download(@PathVariable Long ossId, HttpServletResponse response) throws IOException {
        iSysOssService.download(ossId,response);
    }

    /**
     * 删除OSS对象存储
     *
     * @param ossIds OSS对象ID串
     */
    @SaCheckPermission("system:oss:remove")
    @Log(title = "OSS对象存储", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ossIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ossIds) {
        return toAjax1(iSysOssService.deleteWithValidByIds(Arrays.asList(ossIds), true));
    }

    /**
     * 获取文档处理统计
     */
    @SaCheckPermission("system:oss:list")
    @GetMapping("/stats")
    public R<Map<String, Object>> getStats() {
        Map<String, Object> stats = iSysOssService.getDocumentStats();
        return R.ok(stats);
    }
}
